﻿using System;
using System.Collections.Generic;
using FioBook.Models;
using FioBook.Repositories;

namespace FioBook.Data
{
    public class UnitOfWorkData : IUnitOfWork
    {
        private readonly ApplicationDbContext context;
        private readonly Dictionary<Type, object> repositories = new Dictionary<Type, object>();

        public UnitOfWorkData()
            : this(new ApplicationDbContext())
        {
        }

        public UnitOfWorkData(ApplicationDbContext context)
        {
            this.context = context;
        }

        //public UsersRepository UsersRepository
        //{
        //    get
        //    {
        //        return (UsersRepository)this.GetRepository<ApplicationUser>();
        //    }
        //}

        public IRepository<Team> TeamRepository
        {
            get
            {
                return this.GetRepository<Team>();
            }
        }

        public IRepository<Employee> EmployeeRepository
        {
            get
            {
                return this.GetRepository<Employee>();
            }
        }

        public int SaveChanges()
        {
            return this.context.SaveChanges();
        }

        public void Dispose()
        {
            this.context.Dispose();
        }

        private IRepository<T> GetRepository<T>() where T : class
        {
            if (!this.repositories.ContainsKey(typeof(T)))
            {
                var type = typeof(GenericRepository<T>);

                //if (typeof(T).IsAssignableFrom(typeof(Employee)))
                //{
                //    type = typeof (EmployeeRepository);
                //}
                //else if(typeof(T).IsAssignableFrom(typeof(Team)))
                //{
                //    type = typeof (TeamRepository);
                //}

                this.repositories.Add(typeof(T), Activator.CreateInstance(type, this.context));
            }

            return (IRepository<T>)this.repositories[typeof(T)];
        }
    }
}
